<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .wrap {
            width: 320px;
            height: 500px;
            margin: 50px auto;
            border: 1px solid #333;
            position: relative;

            .box {
                width: 40px;
                height: 40px;
                background-color: aquamarine;
                position: absolute;
                left: 0;
                top: 0;

            }
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="box"></div>
    </div>
</body>
<script>

    var box = document.querySelector(".box");
    var wrap = document.querySelector(".wrap");


    var maxLeft = wrap.clientWidth - box.clientWidth;
    var maxTop = wrap.clientHeight - box.clientHeight;

    document.onkeydown = function (e) {
        var keyCode = e.keyCode;
        console.log(e.key, keyCode);


        var x = box.offsetLeft;
        var y = box.offsetTop;
        var speed = 10;

        switch (keyCode) {
            case 65: // 左 a
                x -= speed;
                break;
            case 87: // 上 w
                y -= speed;
                break;
            case 68: // 右 d 
                x += speed;
                break;
            case 83: // 下 s 
                y += speed;
                break;
        }

        if (x < 0) x = 0;
        if (x > maxLeft) x = maxLeft;
        if (y < 0) y = 0;
        if (y > maxTop) y = maxTop;


        box.style.left = x + "px";
        box.style.top = y + "px";
    }


</script>

</html>